/*
 * Copyright (c) 2001-2018 GuaHao.com Corporation Limited. All rights reserved.
 * This software is the confidential and proprietary information of GuaHao Company.
 * ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the license agreement you entered into with GuaHao.com.
 *
 */
package com.bolt.convention.validation.validators;


import com.bolt.convention.validation.constraints.IDCard;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 身份证格式校验
 */
public class IDCardValidator implements ConstraintValidator<IDCard, String> {
    private static final int CARD_LEN_FIFTEEN = 15;
    private static final int CARD_LEN_EIGHTEEN = 18;

    private boolean allowOld;
    private boolean checkLastCode;

    @Override
    public void initialize(IDCard constraintAnnotation) {
        this.allowOld = constraintAnnotation.allowOld();
        this.checkLastCode = constraintAnnotation.checkLastCode();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        if (value.length() == CARD_LEN_EIGHTEEN) {
            return IDCardValidatorUtil.validate(value, checkLastCode);
        } else {
            return allowOld && value.length() == CARD_LEN_FIFTEEN && IDCardValidatorUtil.validateOld(value);
        }
    }
}
